package cn.moon.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class ProxyMessageDecoder extends ByteToMessageDecoder {


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

        log.debug("======== ProxyMessageDecoder decode ========");

        ProxyMessage proxyMessage = new ProxyMessage();

        // 首字节为消息类型
        byte type = in.readByte();

        // 授权码
        int authorizationCodeLength = in.readByte();
        byte[] authorizationCodeBytes = new byte[authorizationCodeLength];
        in.readBytes(authorizationCodeBytes);
        String authorizationCode = new String(authorizationCodeBytes, CharsetUtil.UTF_8);

        // 信道id
        int channelIdLength = in.readByte();
        byte[] channelIdLengthBytes = new byte[channelIdLength];
        in.readBytes(channelIdLengthBytes);
        String channelId = new String(channelIdLengthBytes, CharsetUtil.UTF_8);

        // 数据区
        int dataLength = in.readInt();
        byte[] dataBytes = new byte[dataLength];
        in.readBytes(dataBytes);

        proxyMessage.setType(type);
        proxyMessage.setChannelId(channelId);
        proxyMessage.setAuthorizationCode(authorizationCode);
        proxyMessage.setData(dataBytes);

        out.add(proxyMessage);

    }


}
